var fs=require("fs");

exports.add=[
{
	_type:"controller",
	_config_details: {	
	},
	_config: {
		path:"adminpanel/",
		name:"AdminTemplates",
		admin:1,
		role_code:"design"
	},
	
	_admin_nav: [
		{section:"design",name:"Page templates",mode:"index"}
	],

	/**
	 * Controller: AdminTemplates.index 
	 *
	 * Returns:
	 *		HTML
	 */
	index: function(config) {
		var t=this;
		this.items=[];
		this.site.models.Template.List("list").forEach(function(tmpl) {
			t.items.push({
				id:tmpl.id,
				name:tmpl.name,
				code:tmpl.code,
				places_cnt:t.site.models.TemplatePlace.Count("count_of_template",{template_id:tmpl.id}),
				pages_cnt:t.site.models.Page.Count("count_of_template",{template_id:tmpl.id})
			});
		});
		return this.Cview();
	},

	/**
	 * Controller: AdminTemplates.edit
	 *
	 * Returns:
	 *		HTML
	 */
	edit: function(config) {
		if (this.fields.id) {
			this.template=this.site.models.Template.Get(this.fields.id);
		} else {
			this.template=this.site.models.Template.Create();
		}
		this.dictionaries={
			template_place_types:this.site.models.TemplatePlaceType.List("list")
		};
		this.template_places=this.site.models.TemplatePlace.List("list_of_template",{template_id:this.fields.id});
		if (this.fields.id) {
			var f=new fs.File(this.site.paths.views+"pagetemplates/"+this.fields.id+".html");
			if (f.exists()) {
				f.open("r");
				this.template.tmpltext=f.read().toString("utf-8");
				f.close();
			}
		}
		return this.Cview();
	},

	/**
	 * Controller: AdminTemplates.save 
	 *
	 * Returns:
	 *		JSON Object
	 */
	save: function(config) {
		var t=this;
		var template;
		if (this.fields.id) {
			template=this.site.models.Template.Get(this.fields.id);
		} else {
			template=this.site.models.Template.Create();
		}
		template.ApplyAdminFields(this.fields);
		template.SaveAll();
		var grid=this.F("ajajform","parse_grid","places");
		this.F("ajajform","save_grid",grid,"TemplatePlace",{
					existing_list:"list_of_template",
					existing:function() { return {template_id:template.id} },
					insert:function(premodel,id) { premodel.template_id=template.id; },
					"delete":function(m) {
						t.site.sql.execute("page_blocks/delete_of_place",{place_id:m.id});
					}
			});
		return JSON.stringify({redirect:{url:this.action}});
	},

	/**
	 * Controller: AdminTemplates.delete
	 *
	 * Returns:
	 *		HTML
	 */
	"delete": function(config) {
		this.template=this.site.models.Template.Get(this.fields.id);
		return this.Cview();
	},

	"delete2": function(config) {
		var t=this;
		var template=this.site.models.Template.Get(this.fields.id);
		var template_places=this.site.models.TemplatePlace.List("list_of_template",{template_id:this.fields.id});
		template_places.forEach(function(tp) { tp.Delete(); });
		template.Delete();
		return JSON.stringify({redirect:{url:this.action}});
	}
}];

